<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\controller\Admin;
use think\Request;
use think\facade\Db;

class Product extends Admin
{
    protected $with = ['product_class','specification_sku','specification_key.specification_value'];
    protected $popup_size = ['width'=>'1000px','height'=>'700px'];
    public function initialize()
    {
        $this->menu_input = [
            'all' => [
                ['type' => 'text', 'name' => '商品名称', 'key' => 'name','verify'=>'required'],
                ['type' => 'select', 'name' => '所属类型', 'key' => 'product_class_id','verify'=>'required',
                    'select'=>[
                        'table'=>'ProductClass'
                    ]
                ],
                ['type' => 'radio', 'name' => '支付类型', 'key' => 'type',
                    'data'=>[
                        1=>'微信支付',
                        2=>'货到付款',
                        3=>'微信+货到'
                    ],
                    'required'=>2
                ],
                ['type' => 'radio', 'name' => '置顶', 'key' => 'is_top',
                    'data'=>[
                        1=>'是',
                        2=>'否'
                    ],
                    'required'=>2
                ],
                ['type' => 'radio', 'name' => '上架', 'key' => 'status',
                    'data'=>[
                        1=>'是',
                        2=>'否'
                    ],
                    'required'=>1
                ],
                ['type' => 'content', 'name' => '内容', 'key' => 'content'],

            ],
            'add' => [

            ],
            'upload' => [

            ],
        ];
        if(input('parent')){
            $this->menu_input['all'][0]['select']['where'] = ['key'=>'parent_id','value'=>input('parent')];
        }
        parent::initialize(); // TODO: Change the autogenerated stub
    }
    
    public function file_y_d()
    {
        $num = random(4);
        $param = $_FILES;
        if (!empty($param)) {
            $file = $param['file'];
            $param = upload_file($file, 1024 * 1024 * 15);
            if (!$param) {
                return msgerror($GLOBALS['upload_file_error']);
            }
        }
        $param['id'] = $num;
        return datasuccess($param);
    }
    public function table_mage(&$data = [])
    {
        $data = [
            ['field' => 'class', 'title' => '类型'],
            ['field' => 'name', 'title' => '商品'],
            ['field' => 'salas', 'title' => '销量'],
            ['field' => 'is_top', 'title' => '置顶'],
            ['field' => 'create_time', 'title' => '添加时间'],
            ['field' => 'update_time', 'title' => '修改时间'],
            ['title' => '操作', 'templet' => '#list_setting','width'=>'15%']
        ];
        return parent::table_mage($data); // TODO: Change the autogenerated stub
    }
    public function index()
    {
        $class = app('app\admin\model\ProductClass');
        $class = $class->select()->toArray();
        $this->assign('class',$class);
        return parent::index(); // TODO: Change the autogenerated stub
    }

    public function index_handle(&$data)
    {
        $data['data'] = array_map(function($v){
            if($v['is_top'] == 1){
                $v['is_top'] = '置顶中';
            }else{
                $v['is_top'] = '未置顶';
            }
            $v['class'] = $v['product_class']['name'];
            $v['salas'] = 0;
            foreach ($v['specification_sku'] as $vv){
                $v['salas'] += ($vv['sales']*1);
            }
            return $v;
        },$data['data']);
        return parent::index_handle($data); // TODO: Change the autogenerated stub
    }
    
    //添加-页面
    public function add()
    {
        $ProductClass_model = app('app\admin\model\ProductClass');
        $class = $ProductClass_model->select()->toArray();
        $this->assign(['product_class'=>$class]);
        return view();
    }
    //编辑-页面
    public function upload()
    {
        $id = input('id');
        $data = $this->model->where('id', $id)->with($this->with)->find()->toArray();
        $ProductClass_model = app('app\admin\model\ProductClass');
        $class = $ProductClass_model->select()->toArray();
        if(empty($data['images']))
        {
            $data['images'] = [];
        }else{
            $data['images'] = explode(',',$data['images']);
        }
    	$SpecificationKey_model = app('app\admin\model\SpecificationKey');
    	$SpecificationValue_model = app('app\admin\model\SpecificationValue');
        $this->assign(['product_class'=>$class]);
        $this->assign('data', $data);
        return view();
    }
    //删除
    public function delete()
    {
        if (request()->isAjax()) {
            $param = param();
            if (!empty($param)) {
                if (strpos($param['id'], ',')) {
                    //指定ID，批量删除
                    $param['id'] = b_arr($param['id']);
                    $param['id'] = array_filter($param['id']);
                    $param['id'] = implode(',',$param['id']);
                }
                try {
                    $ids = explode(',',$param['id']);
                    $ShoppingCart_model = app('app\api\model\ShoppingCart');
                    $ShoppingCart_model->where('product_id','in',$ids)->select()->delete();
                    // pr($param['id']);
                    $this->model::destroy($ids);
                } catch (\Exception $e) {
                    return msgerror($e->getMessage());
                }
                return datasuccess($param);
            }
        }
    }
    //添加-数据接口
    public function add_ajax()
    {
        if (request()->isAjax()) {
            $post = array_filter(input('post.'));
            if ($post) {
                if(isset($post['images'])){
                    $post['images'] = implode(',',$post['images']);
                }else{
                    $post['images'] = '';
                }
                // if(!isset($post['spe_name']) || !isset($post['spe_val'])) return msgerror('规格是必填数据');
                // if(count($post['spe_name']) < 1){
                //     return msgerror('规格为必填数据');
                // }
                if(isset($post['spe_name'])){
                    foreach ($post['spe_name'] as $k=>$v)
                    {
                        if(isset($post['spe_val'][$k])){
                            foreach ($post['spe_val'][$k] as $kk=>$vv){
                                $post['spe_val'][$k] = array_filter($post['spe_val'][$k]);
                                // if(empty($vv)) return msgerror('规格值不能为空');
                            }
                        }
                        
                    }
                }
                
            	$SpecificationKey_model = app('app\admin\model\SpecificationKey');
            	$SpecificationValue_model = app('app\admin\model\SpecificationValue');
            	$SpecificationSku_model = app('app\admin\model\SpecificationSku');
            	if(strlen($post['name']) > 30){
            	    return msgerror('商品名称不能大于30个');
            	}
            	if(isset($post['spe_name'])){
                    $post['spe_name'] = array_filter($post['spe_name']);
                    if(!empty($post['spe_name'])){
                        foreach($post['spe_name'] as $k=>$v)
                        {
                            if(strlen($v) > 20) return msgerror('规格名称不能大于20个字符');
                        }
                        if(isset($post['spe_val'][$k])){
                            $post['spe_val'][$k] = array_filter($post['spe_val'][$k]);
                            foreach ($post['spe_val'][$k] as $kk=>$vv)
                            {
                                if(strlen($vv) > 20) return msgerror('规格值不能大于20个字符');
                            }
                        }
                    }
            	}
            	$price = $post['jg'];
            	$price = round($price*100);
            	$price = $price/100;
            	if($price > 1000000) return msgerror('价格不能大于1000W');
            	if($post['kc']*1 > 1000000) return msgerror('库存不能大于1000W');
                $this->model->save($post);
                $product_id = $this->model->id;
                //商品添加成功，开始添加规格组数据
                $key_data = [];
                $value_data = [];
                if(isset($post['spe_name'])){
                    $post['spe_name'] = array_filter($post['spe_name']);
                    if(!empty($post['spe_name'])){
                        foreach($post['spe_name'] as $k=>$v)
                        {
                            $jy = $post['jy'][$k];
                            $save = ['product_id'=>$product_id,'name'=>$v,'jy_status'=>$jy];
                            $key_id = Db::name('SpecificationKey')->insertGetId($save);
                            foreach ($post['spe_val'][$k] as $kk=>$vv)
                            {
                                $save = ['product_id'=>$product_id,'name'=>$vv,'specification_key_id'=>$key_id];
        		    			Db::name('SpecificationValue')->insertGetId($save);
                            }
                        }
                    }
                    
                }
                //生成KEY 和 VALUE 后直接查数据库获取对应的数据（直接拿表单数据太难处理了）
        		$res = $SpecificationKey_model->order('id asc')->where([['product_id','=',$product_id],['jy_status','=',1]])->select();
        		if(!empty($res) && !empty($res->toArray())){
        			$res = $res->toArray();
        			$data = [];
        			foreach ($res as $k=>$v){
        				$value = $SpecificationValue_model->order('id asc')->where('specification_key_id','=',$v['id'])->select()->toArray();
        				foreach ($value as $vv){
        					$data[$k][] = $vv['id'];
        				}
        			}
        		}
    			$jg = $post['jg'] ?? 0;
    			$cb = $post['cb'] ?? 0;
    			$yj = $post['yj'] ?? 0;
    			$kc = $post['kc'] ?? 0;
        		if(!isset($data) || empty($data)){
        		    //当data为空时表示规格已被全部禁用。需要使用默认规格数据
    		        $SpecificationSku_model->save(['product_id'=>$product_id,'specification_value_ids'=>0,'price'=>$jg,'cb_price'=>$cb,'yj_price'=>$yj,'stock'=>$kc]);
        		}else{
        		    foreach ($data as $k => $v) {
        			    $sku = getCombinationToString($v);
        			    $sku = array_values($sku);
        			}
        			$data = [];
        			foreach ($sku as $v){
        			    $v = explode(',',(string)$v);
        			    sort($v);
        			    $v = implode(',',$v);
        				$res = $SpecificationSku_model->where([['product_id','=',$product_id],['specification_value_ids','=',$v]])->find();
        				//规格组存在时跳过不添加。
        				if(!empty($res) && !empty($res)) continue;
        				$data[] = ['product_id'=>$product_id,'specification_value_ids'=>$v,'price'=>$jg,'cb_price'=>$cb,'yj_price'=>$yj,'stock'=>$kc,'sales'=>0];
        			}
        			$SpecificationSku_model->saveAll($data);
        		}
        		
            }
            return datasuccess($post);
        }
    }
    

    //编辑-数据接口
    public function upload_ajax()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            if ($post) {
                if(isset($post['images'])){
                    $post['images'] = implode(',',$post['images']);
                }else{
                    $post['images'] = '';
                }
                // if(!isset($post['j_spe_name']) && !isset($post['spe_name'])) return msgerror('规格是必填数据');
                // if(isset($post['spe_name']) && !isset($post['spe_val'])) return msgerror('规格是必填数据');
                // if(isset($post['j_spe_name']) && !isset($post['j_spe_val']) && !isset($post['j_spe_val_add'])) return msgerror('规格是必填数据');
                // if(isset($post['spe_name']) && count($post['spe_name']) < 1 || isset($post['j_spe_name']) && count($post['j_spe_name']) < 1){
                //     return msgerror('规格为必填数据');
                // }
                //判断当新增了规格键时，值是否为空
                if(isset($post['spe_name'])){
                   foreach ($post['spe_name'] as $k=>$v)
                   {
                        if(empty($v) || !isset($post['spe_val'][$k]) || empty($post['spe_val'][$k])) return msgerror('规格值不能为空');
                        foreach ($post['spe_val'][$k] as $kk=>$vv){
                            if(empty($vv)) return msgerror('规格值不能为空');
                        }
                   } 
                }
                //当旧的规格键存在时，判断值是否为空
                if(isset($post['j_spe_name'])){
                   foreach ($post['j_spe_name'] as $k=>$v)
                   {
                        $jy = $post['j_jy'][$k];
                        if(isset($post['j_spe_val'][$k])){
                            if(empty($v) || !isset($post['j_spe_val'][$k]) || empty($post['j_spe_val'][$k])) return msgerror('规格值不能为空');
                            foreach ($post['j_spe_val'][$k] as $kk=>$vv){
                                if(empty($vv)) return msgerror('规格值不能为空');
                            }
                        }
                        if(isset($post['j_spe_val_add'][$k])){
                            if(empty($v) || !isset($post['j_spe_val_add'][$k]) || empty($post['j_spe_val_add'][$k])) return msgerror('规格值不能为空');
                            foreach ($post['j_spe_val_add'][$k] as $kk=>$vv){
                                if(empty($vv)) return msgerror('规格值不能为空');
                            }
                        }
                        
                   } 
                }
                
                $SpecificationKey_model = app('app\admin\model\SpecificationKey');
            	$SpecificationValue_model = app('app\admin\model\SpecificationValue');
            	$SpecificationSku_model = app('app\admin\model\SpecificationSku');
            	if(isset($post['key_id'])){
            	    //当存在久键ID时检测是否有删除操作
            	    $key_data = $SpecificationKey_model->where([['product_id','=',$post['id']]])->select()->toArray();
            	    $key_id = [];
            	    foreach ($key_data as $v)
            	    {
            	        $key_id[] = $v['id'];
            	    }
            	    //禁用旧的规格名
            	    foreach($post['key_id'] as $k=>$v){
            	        $SpecificationKey_model::update(['id'=>$v,'jy_status'=>$post['j_jy'][$k]]);
            	    }
            	    
            	    $key_c = array_diff($key_id,$post['key_id']);
            	    if(!empty($key_c)){
            	        //当存在差值时表示有删除的操作，需要删除对应差值的数据
            	        $key_c = implode(',',$key_c);
            	        $SpecificationKey_model->where('id','in',$key_c)->select()->delete();
            	    }
            	}else{
            	    //当旧键不存在时，需要删除全部已有的键
            	    $SpecificationKey_model->where([['product_id','=',$post['id']]])->select()->delete();
            	}
                //当存在新增规则时
                if(isset($post['spe_name'])){
                    $key_data = [];
                    $value_data = [];
                    foreach($post['spe_name'] as $k=>$v)
                    {
                        $save = ['product_id'=>$post['id'],'name'=>$v];
                        $key_id = Db::name('SpecificationKey')->insertGetId($save);
                        foreach ($post['spe_val'][$k] as $kk=>$vv)
                        {
                            $save = ['product_id'=>$post['id'],'name'=>$vv,'specification_key_id'=>$key_id];
    		    			Db::name('SpecificationValue')->insertGetId($save);
                        }
                    }
                }
                //当旧规格依然存在时，判断内容是否需要重新编辑（不包括删除，删除已在上面完成）
                if(isset($post['j_spe_name'])){
                    $save = [];
                    foreach ($post['j_spe_name'] as $k=>$v){
                        //重新编辑规格键名称
                        $SpecificationKey_model::update(['id'=>$post['key_id'][$k],'name'=>$v]);
                        //编辑规格键旧的规格之
                        $j_vla_id = [];
                        if(isset($post['j_spe_val'][$k])){
                            foreach($post['j_spe_val'][$k] as $kk=>$vv)
                            {
                                $j_vla_id[] = $kk;
                                $SpecificationValue_model::update(['id'=>$kk,'name'=>$vv]);
                            }
                            $xy_value = $SpecificationValue_model->where(['product_id'=>$post['id'],'specification_key_id'=>$post['key_id'][$k]])->select()->toArray();
                            $mysql_val_id = [];
                            foreach ($xy_value as $kk=>$vv)
                            {
                                $mysql_val_id[] = $vv['id'];
                            }
                            $val_c = array_diff($mysql_val_id,$j_vla_id);
                    	    if(!empty($val_c)){
                    	        //当存在差值时表示有删除的操作，需要删除对应差值的数据
                    	        $val_c = implode(',',$val_c);
                    	        $SpecificationValue_model->where('id','in',$val_c)->select()->delete();
                    	    }
                            //新增旧规格键的规格值
                            if(isset($post['j_spe_val_add'][$k])){
                                $add_val = [];
                                foreach ($post['j_spe_val_add'][$k] as $kk=>$vv)
                                {
                                    $add_val[] = ['product_id'=>$post['id'],'specification_key_id'=>$post['key_id'][$k],'name'=>$vv];
                                }
                                $SpecificationValue_model->saveAll($add_val);
                            }
                        }else{
                            if(isset($post['j_spe_val_add'][$k])){
                                $add_val = [];
                                if(!empty($post['j_spe_val_add'][$k]) && is_array($post['j_spe_val_add'][$k])){
                                    foreach ($post['j_spe_val_add'][$k] as $kk=>$vv)
                                    {
                                        $add_val[] = ['product_id'=>$post['id'],'specification_key_id'=>$post['key_id'][$k],'name'=>$vv];
                                    }
                                    $SpecificationValue_model->saveAll($add_val);
                                }
                                
                            }
                        }
                        
                        
                    }
                    
                }
                
                //生成KEY 和 VALUE 后直接查数据库获取对应的数据（直接拿表单数据太难处理了）
        		$res = $SpecificationKey_model->order('id asc')->where([['product_id','=',$post['id']],['jy_status','=',1]])->select();
        		if(!empty($res) && !empty($res->toArray())){
        			$res = $res->toArray();
        			$data = [];
        			foreach ($res as $k=>$v){
        				$value = $SpecificationValue_model->order('id asc')->where('specification_key_id','=',$v['id'])->select()->toArray();
        				foreach ($value as $vv){
        					$data[$k][] = $vv['id'];
        				}
        			}
        		}
        		$jg = $post['jg'] ?? 0;
    			$cb = $post['cb'] ?? 0;
    			$yj = $post['yj'] ?? 0;
    			$kc = $post['kc'] ?? 0;
        		if(!isset($data) || empty($data)){
        		    //当data为空时表示规格已被全部禁用。需要使用默认规格数据
        		    $mr = $SpecificationSku_model->where([['product_id','=',$post['id']],['specification_value_ids','=',0]])->find();
        		    if(!empty($mr) && !empty($mr->toArray()))
        		    {
        		        $mr = $mr->toArray();
        		        $SpecificationSku_model::update(['id'=>$mr['id'],'price'=>$jg,'cb_price'=>$cb,'yj_price'=>$yj,'stock'=>$kc]);
        		    }else{
        		        $SpecificationSku_model->save(['product_id'=>$post['id'],'specification_value_ids'=>0,'price'=>$jg,'cb_price'=>$cb,'yj_price'=>$yj,'stock'=>$kc]);
        		    }
        		}else{
        		    foreach ($data as $k => $v) {
        			    $sku = getCombinationToString($v);
        			    $sku = array_values($sku);
        			}
        			$data = [];
        			
        			foreach ($sku as $v){
        			    $v = (string)$v;
        			    $v = explode(',',$v);
        			    sort($v);
        			    $v = implode(',',$v);
        				$res = $SpecificationSku_model->where([['product_id','=',$post['id']],['specification_value_ids','=',$v]])->find();
        				//规格组存在时跳过不添加。
        				if(!empty($res) && !empty($res)) continue;
        				$data[] = ['product_id'=>$post['id'],'specification_value_ids'=>$v,'price'=>$jg,'cb_price'=>$cb,'yj_price'=>$yj,'stock'=>$kc,'sales'=>0];
        			}
        			$SpecificationSku_model->saveAll($data);
        		}
                $this->model::update($post);
    			
            }
            return datasuccess($post);
        }
    }
}
/**
 * 获取组合的结果
 * [@author](https://my.oschina.net/arthor) 18y
 * @anotherdate 2019-04-27T09:49:44+0800
 * [@param](https://my.oschina.net/u/2303379)       array                         $val 组合内容
 * [@return](https://my.oschina.net/u/556800)      [type]                        [description]
 */
function getCombinationToString($val)
{
    // 保存上一个的值
    static $res = array();
    if(empty($res))
    {
        $res = $val;
    }else{
        // 临时数组保存结合的结果
        $list = array();
        foreach ($res as $k => $v) {
            foreach ($val as $key => $value) {
               $list[$k.','.$key] = $v.','.$value;     
            }
        }
        $res = $list;
    }
    return $res;
}
